#!/usr/bin/env python2
#-*- coding:utf-8 -*-

from socket import *
import getopt
import sys
import datetime
import json
import MySQLdb
import time
sys.path.append("/data/dysms_python/")
from sms import send_sms

# 检查服务器连通性
def MonitorGameService(ip,port):
    try:
        data = b'\x09\x00\x00\x00' + b'heartbeat'
        tctimeClient = socket(AF_INET,SOCK_STREAM)
        tctimeClient.connect((ip,port))
        tctimeClient.send(data.encode())
        data = tctimeClient.recv(1024).decode()
        if data[4,9] == 'heartbeat':
            print 'heartbeat success',ip,port
            tctimeClient.close()
            return True
        else:
            print 'heartbeat fail',ip,port
            tctimeClient.close()
            return False
    except:
        print 'connect fail',ip,port
        return False

# 通知所有人
def SmsAdmin(params):
    admins = ['18813987119']
    for admin in admins:
        send_sms(admin, "贵州智星无限科技有限公司", 'SMS_129763850', params)

class GameMonitor:
    def CheckAllGames(self,conf_json):
        dbinfo = conf_json['master']
        def_db = conf_json['def_database']
        self.db = MySQLdb.connect(dbinfo['mysql_ip'],dbinfo['mysql_loginname'],dbinfo['mysql_loginpwd'],def_db)
        cursor = self.db.cursor()
        sql = "SELECT server_ip,server_port,id from t_server_info where status <> 2"
        cursor.execute(sql)
        results = cursor.fetchall()
        for row in results:
            time1 = datetime.datetime.now().microsecond
            ret = MonitorGameService(row[0],row[1])
            time2 = datetime.datetime.now().microsecond
            between = time2 - time1
            if ret == False:
                if self.UpdateGameStatus(row[2],3) == 1:
                    params = u'{"serverid":"%d","level":"%d","reason":"%s"}' % (row[2],1,'网络连接中断')
                    SmsAdmin(params)
            else:
                if self.UpdateGameStatus(row[2],1) == 1:
                    params = u'{"serverid":"%d","level":"%d","reason":"%s"}' % (row[2],1,'网络连接恢复')
                    SmsAdmin(params)
                print 'server:',row[2],' ms:',between
        self.db.close()

    def UpdateGameStatus(self,server_id,status):
        try:
            cursor = self.db.cursor()
            sql = "UPDATE t_server_info SET status = %d WHERE id = %d" % (status,server_id)
            cursor.execute(sql)
            num = cursor.rowcount
            self.db.commit()
            return num
        except:
            self.db.rollback()
            return 0



if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'monitor_game $conf_file'
        exit
    conf_file = sys.argv[1]
    file = open(conf_file,"r")
    conf_str = file.read()
    conf_json = json.loads(conf_str)
    print conf_json
    _monitor = GameMonitor()
    _monitor.CheckAllGames(conf_json)
